package com.wmyg.antifake.service.impl;

import com.wmyg.antifake.entity.BkUser;
import com.wmyg.antifake.entity.ProductTag;
import com.wmyg.antifake.repository.BkUserRepository;
import com.wmyg.antifake.repository.ProductTagRepository;
import com.wmyg.antifake.service.ProductTagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 王卓逸
 * @program TODO
 * @description TODO
 * @create 2019-06-05
 */
@Service
public class ProductTagServiceImpl implements ProductTagService {

    @Autowired
    BkUserRepository bkUserRepository;

    @Autowired
    ProductTagRepository productTagRepository;

    @Override
    public Boolean saveTag(ProductTag productTag, String username) {
        BkUser user = bkUserRepository.findByUsername(username);
        if (null == user) {
            return false;
        }
        productTag.setOperator(user);
        if (null == user.getCompany()) {
            return false;
        }
        productTag.setCompany(user.getCompany());
        productTagRepository.save(productTag);
        return true;
    }

    @Override
    public Boolean updateTag(ProductTag productTag) {
        ProductTag productTagOld = productTagRepository.findByTagId(productTag.getTagId());
        if (null == productTagOld) {
            return false;
        }
        productTag.setOperator(productTagOld.getOperator());
        productTag.setCompany(productTagOld.getCompany());
        productTag.setCreateTime(productTagOld.getCreateTime());
        productTagRepository.save(productTag);
        return true;
    }

    @Override
    public ProductTag findById(Integer tagId) {
        return productTagRepository.findByTagId(tagId);
    }

    @Override
    public List<ProductTag> findProductTagList(String username) {
        BkUser user = bkUserRepository.findByUsername(username);
        if (null == user || null == user.getCompany()) {
            return null;
        }
        return productTagRepository.findByCompanyOrderByCreateTimeAsc(user.getCompany());
    }

    @Override
    public Page<ProductTag> findProductTagPage(String username, Integer index) {
        BkUser user = bkUserRepository.findByUsername(username);
        if (null == user || null == user.getCompany()) {
            return null;
        }
        return productTagRepository.findByCompanyOrderByCreateTimeAsc(PageRequest.of(index, 10), user.getCompany());
    }

    @Override
    public Boolean delete(Integer tagId) {
        productTagRepository.deleteById(tagId);
        return true;
    }
}
